<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {
  filterValidSampleAdatas,
  filterValidSamples,
  getHeaders,
  splitDataIntoPages,
  transformData
} from "@/utils/method"
import {processTableData} from '@/utils/method'
import indexPdf from '@/components/analysisSheetComponents/waterCapacity/tmpl46/indexPdf.vue'
import Index from "@/components/analysisSheetComponents/component/index.vue";
import Device from "@/components/analysisSheetComponents/component/Device.vue";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 5, // 列数
      "defaultRowHeight": 40, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号"}, // A1
        {"r": 0, "c": 1, "v": "类型"}, // A1
        {"r": 0, "c": 2, "v": "水温（℃）"}, // B1
        {"r": 0, "c": 3, "v": "大气压（mbar）"}, // C1
        {"r": 0, "c": 4, "v": "样品浓度（mg/L）"}, // D1
        {"r": 0, "c": 5, "v": "测定结果"}, // E1
        {"r": 0, "c": 6, "v": "备注"}, // E1
      ], // 初始化数据
      "config": {
        "columnlen": { // 设置列宽
          "0": 200, // 第一列宽度 150px
          "1": 200, // 第二列宽度 120px
          "2": 200, // 第三列宽度 180px
          "3": 200,
          "5": 200,
          "6": 200,
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};

const sheetData = ref('')
const waterForm = ref({
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  }
})
const checkTime = ref('')
const processedData = ref([])
const cdatas = ref([])
const checkDialogVisible = ref(false)
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const showTargetPage = ref(false)
const tableHeaders = ref([])
const tabler = ref([])

const switchAdd = ref(true) //传给组件的

const drawer2 = ref(false)
const sampleSnList = ref([])
// 在组件挂载后初始化 Lucky-sheet
onMounted(() => {
  luckysheet.create(options);   // 初始化表格
  getWaterCapacity()  // 获取表单信息
  // 获取信息
  getMethod()
});


// 获取信息
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates
}


// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true
};
const handleCheckClose = () => {
  checkDialogVisible.value = false
}


// 获取工作表信息
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas

      //处理adata到pdf
      tableHeaders.value = splitDataIntoPages(data.adatas, 20)
      tabler.value = getHeaders(data.adatas, 7)
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}

// 保存新增表单
const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  processedData.value = filterValidSampleAdatas(processTableData(data));
  cdatas.value = filterValidSamples(transformData(processedData.value));
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }
  //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 46,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
}


// 下载
const downloadDetail = async () => {
  showTargetPage.value = true
  await nextTick();
  window.print();
  setTimeout(() => {
    showTargetPage.value = false
  }, 1000);
};

</script>

<template>
  <div class="card">
    <el-card class="box-card" v-show="!showTargetPage">
      <h1 style="text-align: center">水质 溶解氧电极法分析原始记录</h1>
      <div>SXLPHJ/JL/CX-22-46</div>
      <table class="table">
        <tr style="background-color: #f2f2f2">
          <td>任务编号</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.task_name"/>
          </td>
          <td>采样日期</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.sampling_time"/>
          </td>
          <td>分析日期</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.anal_time"/>
          </td>
        </tr>
        <tr>
          <td>分析方法</td>
          <td colspan="4">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.method"/>
          </td>
          <td>样品类别</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.category_id"/>
          </td>
        </tr>
        <Device :water-form="waterForm" :colspan="2"></Device>
        <tr>
          <td>环境温度</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.temperature">
              <template #append>
                <span style="background-color: transparent;color: black">℃</span>
              </template>
            </el-input>
          </td>
          <td>环境湿度</td>
          <td colspan="4">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.humidity">
              <template #append>
                <span style="background-color: transparent;color: black">%RH</span>
              </template>
            </el-input>
          </td>
        </tr>
        <tr style="background-color: #f2f2f2">
          <td>仪器校准时水的温度</td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.yqjzssdwd">
              <template #append>
                <span style="background-color: transparent;color: black">℃</span>
              </template>
            </el-input>
          </td>
          <td colspan="2">仪器校准时大气压</td>
          <td colspan="3">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.yqjzsdqy">
              <template #append>
                <span style="background-color: transparent;color: black">mbar</span>
              </template>
            </el-input>
          </td>
        </tr>
      </table>
      <div id="luckysheet" style="width:100%;height:500px;"></div>
      <table class="table">
        <tr>
          <td style="width: 3%;">备注</td>
          <td colspan="4">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.notes"/>
          </td>
        </tr>
      </table>
    </el-card>
    <div v-show="showTargetPage">
      <indexPdf :waterForm="waterForm" :tableHeaders="tableHeaders" :tabler="tabler"></indexPdf>
    </div>
    <!--    底部公共按钮-->
    <div v-show="!showTargetPage">
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :check-time="checkTime"
             :downloadDetail="downloadDetail"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd"></Index>
    </div>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
  justify-content: center;
}


::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
